package it.aekidna.cleverplatypus.delegate
{
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import org.springextensions.actionscript.context.IApplicationContext;
	import org.springextensions.actionscript.context.IApplicationContextAware;
	
	public class GenericDelegateFactory implements IApplicationContextAware
	{
		private var _interface : Class;
		private var _stubClass : Class;
		private var _realClass : Class;
		
		private var _appContext : IApplicationContext;
		
		public var stubsInfo : IStubsInfo;
		
		
		 
		public function GenericDelegateFactory( )
		{
		}

		public function init() : void
		{
		}
		
		public function set contract( inInterface : Class ) : void
		{
			_interface = inInterface;	
			
			var packageAndName : Array = getQualifiedClassName( _interface ).split("::");
			var namePieces : Array = String(packageAndName[0]).split(".");
			var baseName : String = ( packageAndName[1] as String ).substr( 1 );
			try {
				
				_realClass = getDefinitionByName( namePieces.join( "." ) + "." + baseName ) as Class;
			}
			catch( e : Error )
			{ 
			}
			try {
				var stubName : String =  namePieces.join( "." ) + "." + baseName + "Stub";
				_stubClass = getDefinitionByName( namePieces.join( "." ) + "." + baseName + "Stub" ) as Class;
			}
			catch( e : Error )
			{ 
			}
		}
		
		public function set applicationContext( inContext : IApplicationContext ) : void
		{
			_appContext = inContext;	
		}
			
		public function getInstance() : Object
		{
			var usedClass : Class = 
				stubsInfo.usesStub( _interface ) ? 
				_stubClass : _realClass;
			
			var object : Object = 
				_appContext.getObject( _appContext.getObjectNamesForType( usedClass )[0] );
			return object;
		}

	}
}